<template>
  <div class="ai-assistant-container">
    <header class="chat-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <h1>AI宠物助手</h1>
    </header>

    <div class="chat-container" ref="chatContainer">
      <div class="messages-list">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.isUser ? 'user-message' : 'ai-message']"
        >
          <div class="message-avatar">
            <el-icon v-if="message.isUser"><User /></el-icon>
            <el-icon v-else><ChatRound /></el-icon>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.text)"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="input-container">
      <el-input
        v-model="userInput"
        placeholder="请输入您的问题..."
        :disabled="loading"
        @keyup.enter="sendMessage"
        class="message-input"
        :autosize="{ minRows: 1, maxRows: 4 }"
        type="textarea"
      />
      <el-button
        type="primary"
        :disabled="loading || !userInput.trim()"
        @click="sendMessage"
        class="send-button"
      >
        <el-icon><Position /></el-icon>
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, User, ChatRound, Position } from '@element-plus/icons-vue'
import { marked } from 'marked'
import { fetchEventSource } from '@microsoft/fetch-event-source'

/**
 * 格式化并修正消息文本，然后使用 marked 渲染
 */
function formatMessage(text: string): string {
  if (!text) return '';
  // 修复 markdown 标题缺空格问题（###标题 => ### 标题）
  const correctedText = text.replace(/^(#{1,6})(\S)/gm, '$1 $2');
  // 替换不安全字符避免注入，且交给 marked 解析
  return marked.parse(correctedText.trim());
}


interface Message {
  text: string
  isUser: boolean
  timestamp: Date
}

const router = useRouter()
const chatContainer = ref<HTMLElement | null>(null)
const userInput = ref('')
const loading = ref(false)
let ctrl = new AbortController()

const messages = ref<Message[]>([
  {
    text: '您好！我是萌宠情报局的AI助手，有关于宠物的任何问题都可以问我哦！',
    isUser: false,
    timestamp: new Date()
  }
])

/**
 * 发送消息到后端并处理流式响应
 */
const sendMessage = async () => {
  const question = userInput.value.trim()
  if (!question || loading.value) return

  ctrl = new AbortController()

  messages.value.push({
    text: question,
    isUser: true,
    timestamp: new Date()
  })

  const aiMessageIndex = messages.value.length
  messages.value.push({
    text: '',
    isUser: false,
    timestamp: new Date()
  })

  userInput.value = ''
  loading.value = true
  await scrollToBottom()

  await fetchEventSource('/api/user/ai/chat-stream', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ question }),
    signal: ctrl.signal,

    onopen(response) {
      if (response.ok) return;
      throw new Error(`连接失败: ${response.status} ${response.statusText}`);
    },

    onmessage(event) {
      messages.value[aiMessageIndex].text += event.data;
      scrollToBottom();
    },

    onclose() {
      console.log("SSE连接已由服务器正常关闭");
      loading.value = false;
    },

    onerror(err) {
      loading.value = false;
      if (err.name !== 'AbortError') {
        console.error("SSE连接发生错误:", err);
        messages.value[aiMessageIndex].text += "\n\n抱歉，AI服务连接中断。";
        ElMessage.error('AI服务连接中断');
      }
      throw err;
    }
  });
}

onMounted(() => {
  scrollToBottom();
});

onUnmounted(() => {
  // 组件卸载时中止任何正在进行的请求，防止内存泄漏
  if (loading.value) {
    ctrl.abort();
  }
});

const formatTime = (date: Date): string => {
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const scrollToBottom = async (): Promise<void> => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

const goBack = (): void => {
  router.back()
}
</script>

<style scoped>
/* 原始样式 */
.message-text { line-height: 1.6; white-space: normal; }
.message-text p { margin: 0.5em 0; }
.message-text strong, .message-text b { font-weight: bold; }
.message-text ul, .message-text ol { padding-left: 1.5em; }
.message-text li { margin-bottom: 0.3em; }
.message-text code { background-color: #f6f8fa; padding: 2px 4px; border-radius: 4px; font-family: monospace; }
.ai-assistant-container { width: 100%; min-height: 100vh; margin: 0; padding: 0; font-family: 'PingFang SC', 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, sans-serif; background-color: #f7f9fc; background-image: linear-gradient(to bottom, #e8f4ff, #f7f9fc); position: absolute; left: 0; right: 0; top: 0; bottom: 0; display: flex; flex-direction: column; }
.chat-header { display: flex; align-items: center; padding: 16px 20px; background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; position: sticky; top: 0; z-index: 10; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); border-bottom-left-radius: 16px; border-bottom-right-radius: 16px; }
.back-button { margin-right: 15px; cursor: pointer; font-size: 20px; width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.3s ease; background-color: rgba(255, 255, 255, 0.2); }
.back-button:hover { background-color: rgba(255, 255, 255, 0.3); transform: scale(1.05); }
h1 { margin: 0; font-size: 20px; font-weight: 600; letter-spacing: 0.5px; }
.chat-container { flex: 1; overflow-y: auto; padding: 20px; height: calc(100vh - 140px); max-height: calc(100vh - 140px); scroll-behavior: smooth; }
.messages-list { display: flex; flex-direction: column; gap: 20px; padding-bottom: 15px; max-width: 900px; margin: 0 auto; width: 100%; }
.message { display: flex; margin-bottom: 10px; max-width: 80%; animation: fadeIn 0.3s ease-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.user-message { margin-left: auto; flex-direction: row-reverse; }
.ai-message { margin-right: auto; }
.message-avatar { width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 12px; flex-shrink: 0; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); transition: transform 0.3s ease; }
.message-avatar:hover { transform: scale(1.05); }
.user-message .message-avatar { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; }
.ai-message .message-avatar { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); color: white; }
.message-content { background-color: white; padding: 14px 18px; border-radius: 18px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); position: relative; transition: all 0.3s ease; }
.message-content:hover { box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1); }
.user-message .message-content { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; border-top-right-radius: 4px; }
.ai-message .message-content { background-color: white; border-top-left-radius: 4px; }
.message-text { font-size: 15px; line-height: 1.6; word-break: break-word; }
.message-time { font-size: 12px; color: #999; margin-top: 6px; text-align: right; }
.user-message .message-time { color: rgba(255, 255, 255, 0.8); }
.input-container { display: flex; padding: 16px 20px; background-color: white; border-top: 1px solid rgba(0, 0, 0, 0.05); position: sticky; bottom: 0; z-index: 5; box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05); border-top-left-radius: 16px; border-top-right-radius: 16px; }
.message-input { flex: 1; margin-right: 12px; }
:deep(.el-textarea__inner) { border-radius: 24px; padding: 12px 18px; resize: none; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); border: 1px solid rgba(0, 0, 0, 0.08); transition: all 0.3s ease; }
:deep(.el-textarea__inner:focus) { box-shadow: 0 4px 12px rgba(79, 172, 254, 0.15); border-color: #4facfe; }
.send-button { width: 50px; height: 50px; border-radius: 50%; padding: 0; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); border: none; box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3); transition: all 0.3s ease; }
.send-button:hover:not(:disabled) { transform: scale(1.05); box-shadow: 0 6px 16px rgba(79, 172, 254, 0.4); }
.send-button:disabled { background: linear-gradient(135deg, #c2c2c2 0%, #d7d7d7 100%); box-shadow: none; }
@media (max-width: 768px) { .message { max-width: 90%; } }

/* 正文内容：防止全部加粗 */
.message-text {
  font-size: 15px;
  line-height: 1.6;
  word-break: break-word;
  font-weight: normal; /* ⭐关键修复点 */
}

/* 修复 p 标签过粗问题 */
.message-text :deep(p) {
  font-weight: normal !important;
}

/* Markdown 标题优化：显示正常加粗与字号 */
.message-text :deep(h1),
.message-text :deep(h2),
.message-text :deep(h3),
.message-text :deep(h4),
.message-text :deep(h5),
.message-text :deep(h6) {
  font-weight: bold;
  line-height: 1.4;
  margin: 1em 0 0.5em;
}

.message-text :deep(h1) { font-size: 1.5em; }
.message-text :deep(h2) { font-size: 1.35em; }
.message-text :deep(h3) { font-size: 1.2em; }
.message-text :deep(h4) { font-size: 1.1em; }
.message-text :deep(h5) { font-size: 1em; }
.message-text :deep(h6) { font-size: 0.9em; }

</style>
